import * as THREE from 'three'
import Experience from './Experience'
import Sizes from '../Utils/Sizes'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
export default class Camera {
  experience!: Experience
  sizes!: Sizes
  scene!: THREE.Scene
  canvas!: HTMLCanvasElement
  // two cameras
  perspectiveCamera!: THREE.PerspectiveCamera
  frustrum: number = 5
  orthographicCamera!: THREE.OrthographicCamera
  // controls
  controls!: OrbitControls
  constructor() {
    this.experience = new Experience()
    const { scene, sizes, canvas } = this.experience
    this.sizes = sizes
    this.scene = scene
    this.canvas = canvas
    console.log(this.experience, this.scene, this.sizes)
    // create threejs camera: 分别创建 透视相机 和 正交相机
    this.createPerspectiveCamera()
    this.createOrthographicCamera()
    // create OrbitControls
    this.setOrbitControls()
  }
  createPerspectiveCamera() {
    this.perspectiveCamera = new THREE.PerspectiveCamera(35, this.sizes.aspect, 0.1, 1000)
    this.scene.add(this.perspectiveCamera)
    this.perspectiveCamera.position.y = 1
    this.perspectiveCamera.position.z = 10
  }
  createOrthographicCamera() {
    const { aspect } = this.sizes
    const { frustrum } = this
    this.orthographicCamera = new THREE.OrthographicCamera(
      (-frustrum * aspect) / 2,
      (frustrum * aspect) / 2,
      frustrum / 2,
      -frustrum / 2,
      -100,
      100
    )
    this.scene.add(this.orthographicCamera)
    
    const size = 10
    const divisions = 33
    const gridHelper = new THREE.GridHelper(size, divisions)
    this.scene.add(gridHelper)
    const axesHelper = new THREE.AxesHelper(10)
    this.scene.add(axesHelper)
  }
  setOrbitControls() {
    this.controls = new OrbitControls(this.perspectiveCamera, this.canvas)
    this.controls.enableDamping = true
    this.controls.enableZoom = true
  }
  resize() {
    const { aspect } = this.sizes
    const { frustrum } = this
    this.perspectiveCamera.aspect = aspect
    this.perspectiveCamera.updateProjectionMatrix()
    this.orthographicCamera.left = (-frustrum * aspect) / 2
    this.orthographicCamera.right = (frustrum * aspect) / 2
    this.orthographicCamera.top = frustrum / 2
    this.orthographicCamera.bottom = -frustrum / 2
    this.orthographicCamera.updateProjectionMatrix()
  }
  update() {
    this.controls.update()
  }
}
